package leetcode;

/**
 * 买卖股票最佳时机4
 */
public class Solution57 {
    public int maxProfit(int k, int[] prices) {
        if(prices == null || prices.length == 0){
            return 0;
        }
        int n = prices.length;
        //创建dp数组
        int[][] dp = new int[n][2*k + 1];
        //dp数组初始化
        for(int j = 1;j < 2*k + 1;j+=2){
            dp[0][j] = -prices[0];
        }

        for(int i = 1;i < prices.length;i++){
            for(int j = 0;j < 2*k - 1; j+=2){
                //持有股票
                dp[i][j + 1] = Math.max(dp[i - 1][j + 1],dp[i - 1][j] - prices[i]);
                //不持有股票
                dp[i][j + 2] = Math.max(dp[i - 1][j + 2],dp[i][j + 1] + prices[i]);
            }
        }
        return dp[n-1][2*k];
    }
}
